/**
* Created by wuran on 17/06/26.
* 错误提示页
*/
import React, { Component } from 'react';
import { View, Text, StyleSheet, Platform, TouchableOpacity, Animated } from "react-native";
import { Actions } from "react-native-router-flux";
import Picker from 'react-native-wheel-picker'
import { Dimens } from '../../utils/Assets.js';
const ButtonW = (Dimens.DeviceWidth / 2) - 1;
const PickerH = 220

class CommonDatePicker extends React.Component {

  constructor(props) {
    super(props);

    let defaultDate = props.defaultDate ? props.defaultDate : '1990-01-01';
    this.startYear = props.startYear ? props.startYear : 1900
    this.startMonth = props.startMonth ? props.startMonth : 1
    this.startDay = props.startDay ? props.startDay : 1

    this.endYear = props.endYear ? props.endYear : 2050
    this.endMonth = props.endMonth ? props.endMonth : 1
    this.endDay = props.endDay ? props.endDay : 1

    let ddt = defaultDate.split('-');
    let y = parseInt(ddt[0]) - this.startYear;
    let m = parseInt(ddt[1]) - 1;
    let d = parseInt(ddt[2]) - 1;
    this.dateArray = this._createDateData();
    this.yearKeys = this.getNumStrArray(this.startYear, this.endYear)
    this.monthKeysEnd = this.getNumStrArray(1, this.endMonth)
    this.monthKeys = this.getNumStrArray(1, 12)
    this.state = {
      offset: new Animated.Value(Dimens.DeviceHeight),
      yearSelectIndex: y,
      monthSelectIndex: m,
      daySelectIndex: d,
      dayArray: this._getDayData(y, m),
    };

    this._onYearValueChange = this._onYearValueChange.bind(this);
    this._onMouthValueChange = this._onMouthValueChange.bind(this);
    this._onDayValueChange = this._onDayValueChange.bind(this);
    this._confirm = this._confirm.bind(this);

    this.initialY = Platform.select({ android: true, ios: false });
    this.initialM = Platform.select({ android: true, ios: false });
    this.initialD = Platform.select({ android: true, ios: false });

  }

  componentDidMount() {
    Animated.timing(this.state.offset, { duration: 200, toValue: 0 }).start();
  }
  renderItem(source, selectedValue, onValueChange) {
    return (
      <Picker
        style={{ flex: 1, height: PickerH }}
        selectedValue={selectedValue}
        itemStyle={{ color: "#333333", fontSize: 16, fontWeight: 'bold' }}
        onValueChange={onValueChange}>
        {source.map((value, i) => (<Picker.Item label={value} value={i} key={i} />))}
      </Picker>
    )
  }
  /** 私有方法 */
  _closeModal(callback) {
    Animated.timing(this.state.offset, { duration: 200, toValue: Dimens.DeviceHeight }).start(callback);
  }
  _getDayData(yearIndex, monthIndex) {
    let year = this.dateArray[yearIndex];
    let monthArray = year[this.yearKeys[yearIndex]];
    let month = monthArray[monthIndex];
    let value = this.yearKeys[yearIndex] == this.endYear ? month[this.monthKeysEnd[monthIndex]] : month[this.monthKeys[monthIndex]]
    return value
  }

  _onYearValueChange(index) {
    if (this.initialY) {
      this.initialY = false;
    } else {
      this.setState({ yearSelectIndex: index, dayArray: this._getDayData(index, 0), monthSelectIndex: 0, daySelectIndex: 0 })
    }
  }
  _onMouthValueChange(index) {
    if (this.initialM) {
      this.initialM = false;
    } else {
      this.setState({ monthSelectIndex: index, dayArray: this._getDayData(this.state.yearSelectIndex, index), daySelectIndex: 0 })
    }
  }
  _onDayValueChange(index) {
    if (this.initialD) {
      this.initialD = false;
    } else {
      this.setState({ daySelectIndex: index })
    }
  }
  render() {
    let { offset, yearSelectIndex, monthSelectIndex, daySelectIndex, dayArray } = this.state;
    return (
      <Animated.View style={[styles.container, { transform: [{ translateY: offset }] }]}>
        <View style={{ width: Dimens.DeviceWidth, backgroundColor: 'white' }}>
          <View style={{ height: PickerH, flexDirection: 'row' }}>
            {this.renderItem(this.yearKeys, yearSelectIndex, this._onYearValueChange)}
            {this.renderItem((yearSelectIndex == this.yearKeys.length - 1) ? this.monthKeysEnd : this.monthKeys, monthSelectIndex, this._onMouthValueChange)}
            {this.props.shoDay && this.renderItem(dayArray, daySelectIndex, this._onDayValueChange)}
          </View>
          <View style={{ flexDirection: 'row', borderTopColor: '#f2f2f2', borderTopWidth: 1, marginBottom: Dimens.isIPhoneX ? 15 : 0 }}>
            <TouchableOpacity style={{ width: ButtonW, height: 44, justifyContent: 'center' }} activeOpacity={0.8} onPress={this._closeModal.bind(this, Actions.pop)}>
              <Text style={{ fontSize: 15, color: '#333333', alignSelf: 'center' }}>取消</Text>
            </TouchableOpacity>
            <View style={{ width: 1, backgroundColor: '#f2f2f2' }}></View>
            <TouchableOpacity style={{ width: ButtonW, height: 44, justifyContent: 'center' }} activeOpacity={0.8} onPress={this._closeModal.bind(this, this._confirm)}>
              <Text style={{ fontSize: 15, color: '#333333', alignSelf: 'center' }}>确认</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Animated.View>
    );
  }
  _closeModal(callback) {
    Animated.timing(this.state.offset, { duration: 200, toValue: Dimens.DeviceHeight }).start(callback);
  }
  _confirm() {
    Actions.pop();
    let year = this.yearKeys[this.state.yearSelectIndex];
    let month = this.monthKeys[this.state.monthSelectIndex];
    let day = this.state.dayArray[this.state.daySelectIndex];
    if (this.props.modalCallback) {
      if (this.props.shoDay) {
        this.props.modalCallback(`${year}-${month}-${day}`);
      } else {
        this.props.modalCallback(`${year}-${month}`);
      }
    }
  }
  getNumStrArray(start, end) {
    let result = [];
    for (let i = start; i <= end; i++) {
      if (i > 9) {
        result.push(i + '')
      } else {
        result.push('0' + i)
      }
    }
    return result;
  }
  _createDateData() {
    let date = [];
    for (let i = this.startYear; i <= this.endYear; i++) {
      let month = [];
      let endMonth = i == this.endYear ? this.endMonth : 12
      for (let j = 1; j <= endMonth; j++) {
        let day = [];
        let endDay = 31
        if (j === 2) {
          endDay = (i == this.endYear && j == this.endMonth ? this.endDay : 28)
          for (let k = 1; k <= endDay; k++) {
            if (k > 9) {
              day.push(k + '')
            } else {
              day.push('0' + k)
            }
          }
          if (i % 4 === 0) day.push(29 + '');
        } else if (j in { 1: 1, 3: 1, 5: 1, 7: 1, 8: 1, 10: 1, 12: 1 }) {
          endDay = (i == this.endYear && j == this.endMonth ? this.endDay : 31)
          for (let k = 1; k <= endDay; k++) {
            if (k > 9) {
              day.push(k + '')
            } else {
              day.push('0' + k)
            }
          }
        } else {
          endDay = (i == this.endYear && j == this.endMonth ? this.endDay : 30)
          for (let k = 1; k <= endDay; k++) {
            if (k > 9) {
              day.push(k + '')
            } else {
              day.push('0' + k)
            }
          }
        }
        let _month = {};
        _month[j > 9 ? j : ("0" + j)] = day;
        month.push(_month);
      }

      let _date = {};
      _date[i > 9 ? i : ("0" + i)] = month;
      date.push(_date);
    }

    return date;
  }

}

const styles = StyleSheet.create({
  container: {
    position: "absolute",
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: 'rgba(52,52,52,0.3)',
    justifyContent: 'flex-end',
  },
});

module.exports.CommonDatePicker = CommonDatePicker;
